<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/14
 * Time: 14:41
 * Created by Created by Panxsoft.
 */

namespace App\Models\Customers;

use App\Models\Order\Address;
use App\Models\Order\Order;
use App\Models\Products\Product;
use App\Models\ReturnProduct\ReturnProduct;
use App\Models\Store;
use App\Services\Utils\Guard;
use App\Services\Utils\ImageHelper;
use App\Services\Utils\OSSable;
use App\Services\Utils\UploadFile;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Http\UploadedFile;
use Tymon\JWTAuth\Contracts\JWTSubject as AuthenticatableUserContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

/**
 * @property $email
 * @property $password
 * @property $telephone
 * @property $fax
 * @property $ip
 * @property $account
 * @property $verify_code
 * @property int $customer_group_id
 * @property $status
 * @property string customer_id
 * @property int address_id
 * @property string fullname
 * @property string image
 * @property int store_id
 * @property int language_id
 *
 * @property-read Collection|Address[] addresses
 * @property-read Store store
 * @property Address defaultAddress
 * @property Collection|CustomerWishList[] customerWishLists
 * @property null|string jwt_token
 * @property string dial_code
 *
 * Class Customer
 * @package App\Models\Customers
 * @mixin Builder
 */
class Customer extends Authenticatable implements
    CanResetPasswordContract,
    AuthenticatableUserContract
{
    use UploadFile,OSSable;

    // status 状态,不确定有没有其他
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;

    const GUARD_NAME = 'customer';

    const REGISTER_TYPE_EMAIL = 'email';
    const REGISTER_TYPE_TELEPHONE = 'telephone';

    const LOGIN_TYPE_NORMAL = 'normal';
    const LOGIN_TYPE_SOCIAL = 'socialite';

    const REGISTER_TYPES = [
        self::REGISTER_TYPE_EMAIL,
        self::REGISTER_TYPE_TELEPHONE
    ];

    const LOGIN_TYPES = [
        self::LOGIN_TYPE_NORMAL,
        self::LOGIN_TYPE_SOCIAL
    ];

    const ADDRESS_ID_EMPTY = 0;
    const FULL_NAME_LENGTH = 64;

    protected $guarded = [];

    protected $table = 'customer';

    protected $primaryKey = 'customer_id';
    protected $hidden = ['password'];

    public $timestamps = false;
    public $customer_image_prefix = 'customer';

    protected $casts = [
        'address_id'        => 'int',
        'store_id'          => 'int',
        'customer_group_id' => 'int',
        'customer_id'       => 'int',
        'language_id'       => 'int',
        'status'            => 'int'
    ];

    /**
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey(); // Eloquent model method
    }

    /**
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public static function randomDefaultPwd()
    {
        return rand(100000, 999999);
    }

    /**
     * @used-by $defaultAddress
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function defaultAddress()
    {
        return $this->belongsTo(Address::class, 'address_id', 'address_id');
    }


    /**
     * @return null|string
     * @throws \OSS\Core\OssException
     */
    public function getImageAttribute()
    {
        $route = $this->attributes['image'];

        if (!$route) { return null; }

//        if (CK_FINDER_BACKEND === 'oss') {dd($this->getStaticUrl($route));
//            return $this->getStaticUrl($route);
//        } else {
            return ImageHelper::generateImagePath($route);
//        }
    }


    /**
     * @param $image
     * @return null
     * @throws \Exception
     */
    public function setImageAttribute($image)
    {
        if (! is_file($image)) { return null; }

        // 引入dw-oc下的配置文件，图片上传需要的。
        require_once(base_path('../dw-oc/admin/config.php'));

        if (defined('CK_FINDER_BACKEND') && CK_FINDER_BACKEND === ImageHelper::CK_FINDER_OSS) { // oss图片驱动
            $new_image = $this->uploadPostFile($image, $this->customer_image_prefix);
        } else { // file图片驱动
            $old_image = $this->attributes['image'];
            $new_image = $this->uploadPostFileToFile($image, $this->customer_image_prefix, $old_image);
        }

        $this->attributes['image'] = $new_image;

    }

    public function customerWishLists()
    {
        return $this->hasMany(CustomerWishList::class, 'customer_id', 'customer_id');
    }

    /**
     * @param Product $product
     *
     * @return bool
     */
    public function isProductInWishList(Product $product)
    {
        return (bool) $this->customerWishLists->firstWhere('product_id', $product->product_id);
    }

    /**
     * @used-by $addresses
     */
    public function addresses(): HasMany
    {
        return $this->hasMany(Address::class, 'customer_id', 'customer_id');
    }

    public static function getCustomer($customer_id)
    {
        return (new self)->where('customer_id', $customer_id)
            ->where('status', self::STATUS_ENABLE)
            ->first();
    }

    public function orders()
    {
        return $this->hasMany(Order::class, 'customer_id', 'customer_id');
    }

    /**
     * @return HasMany
     */
    public function returnProducts()
    {
        return $this->hasMany(ReturnProduct::class, 'customer_id', 'customer_id');
    }

    /**
     * @param string $token
     *
     * @return bool
     */
    public function updateJwtToken(string $token)
    {
        return $this->update([
            'jwt_token' => $token,
        ]);
    }

    /**
     * @used-by $store
     */
    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id', 'store_id')
            ->withDefault(Store::defaultAttributes());
    }

    /**
     * @return string
     */
    public static function avatarDefault(): string
    {
        return 'static/customer/avatar_default.png';
    }
}